import { coverPosition } from '@/utils/date'
/**
 * @return
 * firstWeekDay:当月第一天星期几
 * count:当月天数
 * lastWeekDay:当月最后一天星期几
 *
 */
const getDaysOfMonth = time => {
  const date = new Date(time)
  date.setDate(1)
  const firstWeekDay = date.getDay()
  date.setMonth(date.getMonth() + 1)
  date.setDate(1)
  date.setDate(date.getDate() - 1)
  return {
    firstWeekDay,
    count: date.getDate(),
    lastWeekDay: date.getDay()
  }
}

// 生成对应的日期组
const generateDate = (curr, prev, currDate, prevDate) => {
  const dateArr = []

  // 本月位数
  for (let i = 1; i <= curr.count; i++) {
    dateArr.push({
      year: currDate.year,
      month: currDate.month,
      day: i,
      date: parseInt(currDate.year + coverPosition(currDate.month) + coverPosition(i))
    })
  }

  //前补位
  for (let i = 0; i <= curr.firstWeekDay - 1; i++) {
    dateArr.unshift({
      year: prevDate.year,
      month: prevDate.month,
      day: prev.count - i,
      date: parseInt(prevDate.year + coverPosition(prevDate.month) + coverPosition(prev.count - i))
    })
  }
  // 后补位
  let nextMonth = currDate.month + 1
  let nextDate = {
    year: nextMonth > 12 ? currDate.year + 1 : currDate.year,
    month: nextMonth > 12 ? 1 : nextMonth
  }
  for (let i = 1; i <= 6 - curr.lastWeekDay; i++) {
    dateArr.push({
      ...nextDate,
      day: i,
      date: parseInt(nextDate.year + coverPosition(nextDate.month) + coverPosition(i))
    })
  }
  return dateArr
}

// 获取日历一屏的天数
export const getCurrDataOfCalendar = ({ year, month, day = 1 }) => {
  const dateStr = `${year}/${month}/${day}`
  let prevDateStr = null,
    prevDate = null
  const currDate = { year, month }
  if (month === 1) {
    prevDateStr = `${year - 1}/${12}/${day}`
    prevDate = { year: year - 1, month: 12 }
  } else {
    prevDateStr = `${year}/${month - 1}/${day}`
    prevDate = { year, month: month - 1 }
  }
  const currMonthInfo = getDaysOfMonth(dateStr)
  const prevMonthInfo = getDaysOfMonth(prevDateStr)
  return generateDate(currMonthInfo, prevMonthInfo, currDate, prevDate)
}

// 获取当天日期
export const currDayObj = () => {
  const date = new Date()
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate()
  }
}

// 匹配组内期是否是当天

export const isCurrDay = (currDay, item) => {
  return currDay.year == item.year && currDay.month == item.month && currDay.day == item.day
}
